import { CloseOutlined } from "@ant-design/icons";
import { Modal, Select } from "antd";
import React, { useCallback, useState } from "react";
import { EditorFormProps } from "../declare";
import { BannerAddModal } from "./AddBanner";
import { AddControl } from "./AddControl";
import { RemoveControl } from "./RemoveControl";
import styles from './style.less';


type Banner = {
  title: string
  id: string
  link: string
  image_url: string
}




/**
 * editor
 * @param props 
 */
export function useBannerEditor(props: EditorFormProps) {
  // const [banners, setBanners] = useState<Banner[]>([])
  const [visible, setVisable] = useState<boolean>(false)
  const handleAddBanner = useCallback(() => {
    setVisable(true)
  }, [])

  const handleClose = useCallback(() => {
    setVisable(false)
  }, [])


  const hanleOk = useCallback((bannerId: any) => {
    setVisable(false)
    const value = props.value?.strcutData || []
    value.push(bannerId)
    props.onChange({
      ...value
    })
  }, [props])

  const handleRemove = useCallback((item) => {
    const newVal = props.value || {}
        const idx = newVal.strcutData.findIndex(tx => tx.id === item.id)
        if (idx > -1) {
          newVal.strcutData.splice(idx, 1)
        }
        props.onChange({
          ...newVal
        })
  }, [props])
  // useEffect(() => {
  //   if (props.value && props.value.length > 0) {
  //     // 读取banner 信息
  //     getBannanerForTpl(props.value).then(rs => {
  //       if (rs.data) {
  //         setBanners(rs.data)
  //       }
  //     })
  //   }
  // }, [props.value])

  return {
    handleAddBanner,
    visible,
    // banners,
    handleClose,
    hanleOk,
    handleRemove
  }
}


export function BannerEditor(props: EditorFormProps) {

  const { handleAddBanner, visible, handleClose, hanleOk, handleRemove } = useBannerEditor(props);
  return (
    <div className={styles["banner-editor"]}>
      <div className={styles["banner-list"]}>
        {
          props.value?.strcutData?.map(bn => (
            <div className={styles["banner-item"]} key={bn.id}>
              <div className={styles["banner-img"]}>
                <img src={bn.image_url} />
              </div>
              <div className={styles["banner-link"]}>
                <Select placeholder='请选择跳转页面' className={styles["banner-link-input"]}></Select>
              </div>
              <RemoveControl
              
                onRm={()=>handleRemove(bn)}
              />
            </div>
          ))
        }
      </div>

      <AddControl onAdd={handleAddBanner} />
      <BannerAddModal
        open={visible}
        onClose={handleClose}
        onOk={hanleOk}
      />
    </div>
  )

}